import RenderContextMenu from './render-context-menu';
import { renderInner } from './render-inner';
// 渲染节点
export default {
	name: 'OrgChartNode',
	inheritAttrs: false,
	components: {
		RenderContextMenu
	},
	props: {
		// 架构图数据
		/* expand：是否展开节点。
		renderContent:自定义某个节点的整体样式
		label:名称
		children：子节点
		level 界别
		vertical：方向，除了true 都是横向
fullContent:自定义鼠标移动上去显示的内容，默认 部门名称++
		{
			chidlren:[]
		}
		*/
		funPanY: {
			type: Function,
			default: () => {
				return true;
			}
		},
		data: {
			type: Object,
			required: true
		},
		level: {
			type: Number,
			default: -1
		},
		// 数据配置
		props: {
			type: Object,
			default: () => {
				return {};
			}
			// 	{
			// 	label: 'label',
			// 	expand: 'expand',
			// 	children: 'children',
			// 	level: 'level'
			// }
		},
		// 是否水平展开
		horizontal: Boolean,
		// 是否可以折叠展开
		collapsable: Boolean,
		// 显示人数
		hasShowNumber: {
			type: Boolean,
			default: true
		},
		// 显示岗位
		hasShowPost: {
			type: Boolean,
			default: true
		},
		// 显示总人数
		hasShowTotal: {
			type: Boolean,
			default: true
		},
		// 自定义渲染内容
		renderContent: Function,
		// label样式名
		labelClassName: [Function, String],
		// label样式对象
		labelClassStyle: [Function, Object],
		// 统一所有项的宽度
		labelWidth: [Number, String],
		// tl-tooltip配置参数
		tooltipProps: {
			type: Object,
			default() {
				return {
					// 是否启用
					enable: true,
					placement: 'bottom',
					effect: 'light',
					openDelay: 500
				};
			}
		},
		// 右键菜单配置
		contextMenuProps: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	data() {
		return {
			//当前右键对象
			currentContextMenuTarget: null,
			// 当前节点数据
			currentNodeData: {},
			currentLevel: 0
		};
	},
	methods: {
		// 创建 node 节点
		renderNode(h, data) {
			const cls = ['org-chart-node'];
			// 判断是否是子节点:根据children的长度判断
			const isLeaf = this.isLeaf(data, this.props.children);
			if (isLeaf) {
				cls.push('is-leaf');
			} else if (this.collapsable && !data[this.props.expand]) {
				cls.push('collapsed');
			}
			//  子节点
			const childNodes = [];

			// 渲染内容
			const label = this.renderLabel(h, data);

			childNodes.push(label);

			// 渲染子节点
			if (!this.collapsable || data[this.props.expand]) {
				if (
					data[this.props.level] < this.level ||
					(data.isPost && data[this.props.children].length != 0)
				) {
					const children = data[this.props.children];
					const node = this.renderChildren(h, children);
					childNodes.push(node);
				}
			}
			// 节点配置
			const hData = {
				domProps: {
					className: cls.join(' ')
				}
			};
			return h('div', hData, childNodes);
		},
		// 渲染节点内容
		renderLabel(h, data) {
			const label = data[this.props.label];
			const empCount = data[this.props.empCount];
			const headCount = data[this.props.headCount];
			const childNodes = [];
			// 是否有自定义内容
			let renderContent = data.renderContent || this.renderContent;
			if (!!renderContent && typeof renderContent === 'function') {
				const vNode = renderContent(h, data);
				vNode && childNodes.push(vNode);
			} else if (data.isUser) {
				childNodes.push(this.renderEmp(h, data, this.$props));
			} else {
				// 渲染inner
				childNodes.push(renderInner(h, data, this.$props));
				// 填充文本
				// childNodes.push(label);
			}
			// 控制折叠按钮的显示
			if (this.collapsable && !this.isLeaf(data, this.props.children)) {
				const button = this.renderButton(h, data);
				button && childNodes.push(button);
			}

			// label点击事件
			const clickHandler = this.$listeners['on-node-click'];

			// 处理label样式
			const { cls, style } = this.handleLabelStyle(data);
			// 处理tooltip
			const { parentTag, tooltipData } = this.handleToolTip(data);

			// label节点配置
			const hLabelData = {
				domProps: {
					className: 'org-chart-node-label'
				}
			};
			// inner节点配置
			const self = this;
			const hInnerData = {
				domProps: {
					className: cls.join(' ')
				},
				style,
				on: {
					// 点击事件
					click: (e) => {
						clickHandler && clickHandler(data, e);
						self.currentNodeData = data;
						// 隐藏右键
						self.contextMenuProps.enable &&
							self.$refs.contextMenu &&
							self.$refs.contextMenu.hideContextMenu();
					}, // 组织时间冒泡
					mousedown: (e) => {
						e.stopPropagation();
					},
					contextmenu: (e) => {
						e.preventDefault();
						self.currentContextMenuTarget = e;
						self.currentNodeData = data;
					}
				}
			};

			return h('div', hLabelData, [
				h(parentTag, tooltipData, [h('div', hInnerData, childNodes)])
			]);
		},
		changeMore(data, e) {
			e.stopPropagation();
			data.showMore = !data.showMore;
		},
		renderEmp(h, data) {
			let tempData = data.list.filter((item, index) => {
				return data.showMore || index < 2;
			});
			return (
				<div class={'userList'}>
					{' '}
					{tempData.map((item, index) => {
						return (
							<div
								key={index}
								class="item"
								onClick={(e) =>
									this.goUserInfo(item.a0188, item.a0188B, item.status, e)
								}
							>
								<img
									src={'Emp/PublicDlg/ShowPhoto.aspx?EmployeeID=' + item.a0188}
								/>{' '}
								<p> {item.content + ' ' + item.sex} </p>{' '}
							</div>
						);
					})}{' '}
					{data.list.length > 2 ? (
						<div class="more" onClick={(e) => this.changeMore(data, e)}>
							{' '}
							{!data.showMore ? '更多' : '收起'}{' '}
						</div>
					) : (
						''
					)}{' '}
				</div>
			);
		},
		goUserInfo(a0188, a0188B, status, e) {
			console.log(a0188B);
			console.log(status);

			e.stopPropagation();
			// this.$router.push({
			// 	path: '/iframPage',
			// 	query: {
			// 		url: `/WebObject/PersonObjT2.aspx?EmployeeID=${a0188}`
			// 	}
			// });
			// this.$router.push({
			// 	path: '/Org/PersonObj',
			// 	query: {
			// 		EmployeeID: `${a0188}`
			// 	}
			// });

			// this.$router.resolve({
			//     path: '/Org/PersonObj',
			//     query: {
			//         EmployeeID: `${a0188}`
			//     }
			// });
			let top =
				location.search.length > 2
					? location.search + '&hideFrame=1'
					: '?hideFrame=1';
			let routeData = this.$router.resolve({
				path: '/Org/PersonObj',
				query: {
					EmployeeID: `${a0188}`,
					EmployeeIDB: `${a0188B}`,
					status: `${status}`
				}
			});
			window.open(top + routeData.href, '_blank');
		},
		// 处理toolTip
		handleToolTip(data) {
			const label = data[this.props.label];

			// 是否开启 toolTip
			const hasOpenToolTip = !!this.tooltipProps.enable && !data.isUser;
			const parentTag = hasOpenToolTip ? 'el-tooltip' : 'div';
			// el-toolTip配置
			let tooltipData = {};
			if (hasOpenToolTip) {
				tooltipData = {
					props: {
						...this.tooltipProps,
						content: `${label} (当前人数:${data.empCount}人,编制:${data.headCount}人)`
					}
				};
			}
			return {
				parentTag,
				tooltipData
			};
		},
		// 处理label的样式
		handleLabelStyle(data) {
			// 样式控制
			const cls = ['org-chart-node-label-inner'];
			let style = {};

			// 选项宽度
			let labelWidth = data.labelWidth || this.labelWidth;
			if (typeof labelWidth === 'number') {
				labelWidth += 'px';
			}
			labelWidth &&
				(style = {
					width: labelWidth
				});

			// 样式名
			let labelClassName = this.labelClassName;
			if (typeof labelClassName === 'function') {
				labelClassName = this.labelClassName(data);
			}
			labelClassName && cls.push(labelClassName);

			// 样式对象
			let labelClassStyle = data.labelClassStyle || this.labelClassStyle;
			if (typeof labelClassStyle === 'function') {
				labelClassStyle = labelClassStyle(data);
			}
			if (labelClassStyle) {
				style = {
					...labelClassStyle,
					...style
				};
			}
			return {
				style,
				cls
			};
		},
		// 渲染按钮
		renderButton(h, data) {
			// 按钮点击事件
			const expandHandler = this.$listeners['on-expand'];

			const cls = ['org-chart-node-btn'];

			if (data[this.props.expand]) {
				cls.push('expanded');
			}
			// 节点配置
			const hData = {
				// 在导出图片的时候忽略
				attrs: {
					'data-html2canvas-ignore': true
				},
				domProps: {
					className: cls.join(' ')
				},
				on: {
					click: (e) => {
						e.stopPropagation();
						expandHandler && expandHandler(data);
					}
				}
			};
			return h('span', hData);
		},
		// 渲染子节点
		renderChildren(h, list) {
			if (Array.isArray(list) && list.length) {
				// 循环创建node节点
				const childNodes = list.map((item) => {
					return this.renderNode(h, item);
				});
				// 节点配置
				const hData = {
					domProps: {
						className: 'org-chart-node-children'
					}
				};
				return h('div', hData, childNodes);
			}
			return '';
		},
		// 渲染右键菜单
		renderContextMenuList(h, data) {
			const self = this;
			// 过滤右键监听事件
			let events = {};
			Object.keys(self.$listeners).forEach((key) => {
				if (key.includes('context-click')) {
					events[key] = self.$listeners[key];
				}
			});
			const hData = {
				props: {
					data: this.currentNodeData,
					target: this.currentContextMenuTarget,
					contextMenuList: this.contextMenuProps.menuList,
					funPanY: this.funPanY
				},
				on: {
					...events
				},
				ref: 'contextMenu'
			};
			return h('render-context-menu', hData);
		},
		// 是否是子节点
		isLeaf(data, prop) {
			const hasChildren = !(Array.isArray(data[prop]) && data[prop].length > 0);

			// 显示的级别
			let hasLastLevel = false;
			// if (!this.collapsable) {
			hasLastLevel = data[this.props.level] === this.level;
			// }
			return hasChildren || hasLastLevel;
		}
	},
	render(h) {
		// 渲染节点
		const nodes = [];
		const node = this.renderNode(h, this.data);
		nodes.push(node);
		// 是否添加右键菜单
		if (this.contextMenuProps.enable) {
			const contextMenu = this.renderContextMenuList(h, this.data);
			nodes.push(contextMenu);
		}
		return h(
			'div',
			{
				domProps: {
					className: 'org-chart-node-warp'
				}
			},
			nodes
		);
	}
};
